package com.grade.util;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
import java.util.logging.Logger;

public class CaptchaUtil {

    private static final String CAPTCHA_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final int CAPTCHA_WIDTH = 150;
    private static final int CAPTCHA_HEIGHT = 50;
    private static final Logger LOGGER = Logger.getLogger(CaptchaUtil.class.getName());

    /**
     * 生成验证码文本
     * @return 返回生成的验证码文本
     */
    public static String generateCaptchaText() {
        Random random = new Random();
        StringBuilder captchaText = new StringBuilder();
        for (int i = 0; i < 2; i++) {
            int index = random.nextInt(CAPTCHA_CHARS.length());
            captchaText.append(CAPTCHA_CHARS.charAt(index));
        }

        // 记录生成的验证码文本
        LOGGER.info("Generated Captcha Text: " + captchaText.toString());

        return captchaText.toString();
    }

    /**
     * 生成验证码图片
     * @param captchaText 验证码文本
     * @return 返回生成的验证码图片
     */
    public static BufferedImage generateCaptchaImage(String captchaText) {
        BufferedImage image = new BufferedImage(CAPTCHA_WIDTH, CAPTCHA_HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        Random random = new Random();

        // 设置背景颜色
        g.setColor(new Color(255, 255, 255));
        g.fillRect(0, 0, CAPTCHA_WIDTH, CAPTCHA_HEIGHT);

        // 设置字体
        g.setFont(new Font("Arial", Font.BOLD, 40));

        // 绘制验证码文本
        g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
        g.drawString(captchaText, 30, 40);

        // 绘制干扰线
        for (int i = 0; i < 3; i++) {
            g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            g.drawLine(random.nextInt(CAPTCHA_WIDTH), random.nextInt(CAPTCHA_HEIGHT),
                    random.nextInt(CAPTCHA_WIDTH), random.nextInt(CAPTCHA_HEIGHT));
        }

        g.dispose();
        // 记录生成的验证码文本
        LOGGER.info("Generated Captcha ImageText: " + captchaText.toString());
        return image;
    }
}
